package multithread.pool.threadPool;

import lombok.val;
import util.ThreadUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: zhangrongqing
 * @Date: 2019/12/20 10:45
 */
public class DefaultThreadPoolDemo<Job extends Runnable> implements ThreadPoolDemo<Job> {

    private final static Integer Default_Work_Size = 10;
    private final static Integer Work_MAX_Size = 20;
    private static Integer Work_Initial_Size = 1;

    private LinkedList<Job> jobs = new LinkedList<>();
    private List<Work> works = new ArrayList<>();

    public DefaultThreadPoolDemo(){
        initial();
    }

    @Override
    public void initial() {
        for (int i = 0; i < Work_Initial_Size; i++) {
            Work work = new Work();
            work.start();
//            Thread thread = new Thread(work);
//            thread.start();
            works.add(work);
        }
    }

    @Override
    public void addWorkNum(int num) {

    }

    @Override
    public void excute(Job job) {
        synchronized (jobs){
            //加入任务，通知消息
            jobs.addLast(job);
            jobs.notify();
        }
    }

    @Override
    public int getJobSize() {
        return jobs.size();
    }

    @Override
    public void shutdown() {
        for (Work work : works) {
            work.shutdown();
        }
    }

    private class Work extends Thread {
        private static final String WORKNAME = "ThreadPool-Test";

        @Override
        public void run() {
            Job job;
//            while(!Thread.currentThread().isInterrupted()){
            synchronized (jobs) {
                if (jobs.isEmpty()) {
                    try {
                        //等待工作
                        jobs.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                job = jobs.removeLast();
            }
            job.run();
//            }
        }

        public void shutdown() {
            Thread.currentThread().destroy();
        }
    }

    public static void main(String[] args) {
        DefaultThreadPoolDemo defaultThreadPoolDemo= new DefaultThreadPoolDemo<>();
//        defaultThreadPoolDemo.initial();
        for (int i = 0; i < 10; i++) {
            ThreadUtil.sleep(1000);
            defaultThreadPoolDemo.excute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+" 123");
                    ThreadUtil.sleep(10000);
                    System.out.println("======================");
                }
            });
        }

    }
}
